
import {
	HTTP_REQUEST_URL,
	AppID,
	HEADER,
	HEADERPARAMS,
	HEADERFORM,
	TOKENNAME,
	EXPIRE
}
from "@/config/app.js"
function baseRequest (url, method,data, {
	noAuth = false,
	isImage = false,
	isUploadFile = false 
}, params){
	let Url = `/b/api`;  //打包到线上 需要加上/b或/a等前缀
// 	let Url = `/api`;  //本地开发环境不需要加前缀
	let	header = HEADER;
	let token = uni.getStorageSync('userToken');
	if(params != undefined){
		header = HEADERPARAMS
	}
	if(!noAuth){
		//需要token认证
		if(token){
			header[TOKENNAME] = token
		}
	}
    if(isUploadFile){
		//上传图片或者文件
		header = HEADERFORM
		console.log("上传----",header)
		return new Promise((resolve,reject)=>{
			uni.uploadFile({
			    url: Url + url,
			    method: method || 'GET',
			    filePath: data || '',
				name: 'file',
			    success: (response) => {
					const data = JSON.parse(response.data);
					console.log(data,data.retCode);
					if (data.retCode == 'SUCCESS') {
						
						resolve(data.retData); //正常拿到数据
					}else if(data.retCode == "SESSIONTIMEOUT"){
						//会话已过期
						uni.navigateTo({
							url:'/pages/reLogin/reLogin'
						})
						resolve(data); 
					}else if (data.retCode == 'NOREGISTER') {
						
						//未注册
						uni.showToast({
							title: data.retMsg,
							icon: "none"
						})
						uni.navigateTo({
							url:'/pages/login/login'
						})
						resolve(data); 
						
					}else if (data.retCode == 'FAIL') {
						uni.showToast({
							title: data.retMsg,
							icon: "none"
						})
					}
			    },
				fail(err) {
					console.log('文件上传失败');
					reject(err)
				}
			});
		})
	}else{ 
		return new Promise((resolve,reject)=>{
			uni.request({
			    url: Url + url,
			    method: method || 'GET',
			    header: header,
			    data: data || {},
			    success: (response) => {
					const data = response.data;
					if (data.retCode == 'SUCCESS') {
						 resolve(data); //正常拿到数据
					}else if(data.retCode == "SESSIONTIMEOUT"){
						//会话已过期
						uni.navigateTo({
							url:'/pages/reLogin/reLogin'
						})
						resolve(data); 
					}else if (data.retCode == 'NOREGISTER') {
						
						//未注册
						uni.showToast({
							title: data.retMsg,
							icon: "none"
						})
						uni.navigateTo({
							url:'/pages/login/login'
						})
						resolve(data); 
						
					}else if (data.retCode == 'FAIL') {
						uni.showToast({
							title: data.retMsg,
							icon: "none"
						})
					}else if(response.statusCode == '200'){
						resolve(data); 
					}
			    },
				fail(err) {
					reject(err)
				}
			});
		})
	} 
	
}
const request = {};
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt, params) => baseRequest(api, method, data, opt || {}, params)
});
export default request;
